package com.koron.util;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.*;
import java.net.*;
import java.util.*;
import java.util.Map.Entry;


public class HttpUtil {
	
	private static Integer connectTimeout = 5000;
	private static Integer socketTimeout = 6000;
	private static String proxyHost = null;
	private static Integer proxyPort = null;

	private static Logger logger = Logger.getLogger(HttpUtil.class);

	public static String sendPost(String url, String param) throws Exception {
		PrintWriter out = null;
		String result = "";
		DataInputStream dis=null;
		logger.debug("url=" + url  + ";param=" + param);
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/Json; charset=UTF-8");
			conn.setConnectTimeout(10000);
			conn.setReadTimeout(50000);
			//conn.setRequestProperty("contentType", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
//			out = new PrintWriter(conn.getOutputStream());
//			// 发送请求参数
//			out.print(param);
//			// flush输出流的缓冲
//			out.flush();
			OutputStream os =  conn.getOutputStream();
			os.write(param.getBytes("UTF-8"));
			os.flush();
			// 定义BufferedReader输入流来读取URL的响应
			byte[] bs = new byte[0];
			byte[] btemp = new byte[1024];
			int count =0;
			dis = new DataInputStream(conn.getInputStream());
			while((count = dis.read(btemp))>-1) {
				byte[] temp = bs;
				bs=new byte[temp.length+count];
				System.arraycopy(temp, 0, bs, 0, temp.length);
				System.arraycopy(btemp, 0, bs, temp.length, count);
			}
			result = new String(bs, "UTF-8");
			logger.debug("url=" + url + ";return" + result);
		}catch(Exception e) {
			logger.error(url, e);
			throw e;
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (dis != null) {
					dis.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 以Content-Type: multipart/form-data的形式发送post请求
	 * @param url
	 * @param map
	 * @return
	 * @throws Exception
	 */
	public static String doPostForm(String url, HashMap<String, String> map) throws Exception {
		String result = "";
		CloseableHttpClient client = null;
		CloseableHttpResponse response = null;
		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(550000).setConnectTimeout(550000)
				.setConnectionRequestTimeout(550000).setStaleConnectionCheckEnabled(true).build();
		client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
		// client = HttpClients.createDefault();
		URIBuilder uriBuilder = new URIBuilder(url);

		HttpPost httpPost = new HttpPost(uriBuilder.build());
		httpPost.setHeader("Connection", "Keep-Alive");
		httpPost.setHeader("Charset", "UTF-8");
//		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httpPost.setHeader("Content-Type", "multipart/form-data");
		Iterator<Entry<String, String>> it = map.entrySet().iterator();
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
			params.add(pair);
		}

		httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
		try {
			response = client.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, "UTF-8");
				}
			}
		} catch (ClientProtocolException e) {
			throw new RuntimeException("创建连接失败" + e);
		} catch (IOException e) {
			throw new RuntimeException("创建连接失败" + e);
		}

		return result;
	}


	public static String sendGet(String url, Map<String, Object> param) throws Exception {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key).toString());
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "utf-8");
			}
		} catch (Exception e) {
			logger.error("调用失败",e);
			throw new Exception(response.toString(),e);
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			}
		}
		return resultString;
	}

	public static String sendGet(String url) throws Exception {
		return sendGet(url, null);
	}

	public static String getEncoding(String str) {
		String encode = "GB2312";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GB2312
				String s = encode;
				return s; //是的话，返回“GB2312“，以下代码同理
			}
		} catch (Exception exception) {
		}
		encode = "ISO-8859-1";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是ISO-8859-1
				String s1 = encode;
				return s1;
			}
		} catch (Exception exception1) {
		}
		encode = "UTF-8";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是UTF-8
				String s2 = encode;
				return s2;
			}
		} catch (Exception exception2) {
		}
		encode = "GBK";
		try {
			if (str.equals(new String(str.getBytes(encode), encode))) { //判断是不是GBK
				String s3 = encode;
				return s3;
			}
		} catch (Exception exception3) {
		}
		return "";
	}
	
	
	/**
	 * Do GET request
	 * 
	 * @param url
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	public String doGet(String url, Map<String, String> parameterMap, Map<String, String> headers) throws Exception {
		String params = mapToQueryString(parameterMap);
		if(params.length() > 0){
			url = url.indexOf("?") != -1 ? (url + "&" + params.toString()) : (url + "?" + params.toString());
		}
		URL localURL = new URL(url);
		URLConnection connection = openConnection(localURL);
		renderRequest(connection);
		HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
		httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
		if(headers != null && headers.size() > 0) {
			Set<Entry<String, String>> set = headers.entrySet();
			Iterator<Entry<String, String>> iterator = set.iterator();
			while(iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
			}
		}
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuffer resultBuffer = new StringBuffer();
		String tempLine = null;
		if (httpURLConnection.getResponseCode() >= 300) {
			throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
		}
		try {
			inputStream = httpURLConnection.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			while ((tempLine = reader.readLine()) != null) {
				resultBuffer.append(tempLine);
			}
		} finally {
			if (reader != null) {
				reader.close();
			}
			if (inputStreamReader != null) {
				inputStreamReader.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
		return resultBuffer.toString();
	}

	/**
	 * Do POST request
	 * 
	 * @param url
	 * @param parameterMap
	 * @return
	 * @throws Exception
	 */
	public static String doPost(String url, Map<String, String> parameterMap, Map<String, String> headers) throws Exception {
		String params = mapToQueryString(parameterMap);
		return doPost(url, params, headers);
	}
	
	public static String doPost(String url, String params, Map<String, String> headers) throws Exception {
		URL localURL = new URL(url);
		URLConnection connection = openConnection(localURL);
		HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setRequestMethod("POST");
		if(headers != null && headers.size() > 0) {
			Set<Entry<String, String>> set = headers.entrySet();
			Iterator<Entry<String, String>> iterator = set.iterator();
			while(iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
			}
		}
		httpURLConnection.setRequestProperty("Accept-Charset", "UTF-8");
		httpURLConnection.setRequestProperty("Content-Length", String.valueOf(params.length()));
		OutputStream outputStream = null;
		OutputStreamWriter outputStreamWriter = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		BufferedReader reader = null;
		StringBuffer resultBuffer = new StringBuffer();
		String tempLine = null;
		try {
			outputStream = httpURLConnection.getOutputStream();
			outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
			outputStreamWriter.write(params);
			outputStreamWriter.flush();
			if (httpURLConnection.getResponseCode() >= 300) {
				throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
			}
			inputStream = httpURLConnection.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			reader = new BufferedReader(inputStreamReader);
			while ((tempLine = reader.readLine()) != null) {
				resultBuffer.append(tempLine);
			}
		} finally {
			if (outputStreamWriter != null) {
				outputStreamWriter.close();
			}
			if (outputStream != null) {
				outputStream.close();
			}
			if (reader != null) {
				reader.close();
			}
			if (inputStreamReader != null) {
				inputStreamReader.close();
			}
			if (inputStream != null) {
				inputStream.close();
			}
		}
		return resultBuffer.toString();
	}
	
	public static String mapToQueryString(Map<String, String> map) {
		StringBuilder buil = new StringBuilder("");
		if (map != null) {
			Set<Entry<String, String>> set = map.entrySet();
			Iterator<Entry<String, String>> iterator = set.iterator();
			while(iterator.hasNext()) {
				Entry<String, String> entry = iterator.next();
				buil.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
			}
			if(buil.length() > 0){
				buil = buil.delete(buil.length() - 1, buil.length());
			}
		}
		return buil.toString();
	}

	private static URLConnection openConnection(URL localURL) throws IOException {
		URLConnection connection;
		if (proxyHost != null && proxyPort != null) {
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
			connection = localURL.openConnection(proxy);
		} else {
			connection = localURL.openConnection();
		}
		return connection;
	}

	/**
	 * Render request according setting
	 * 
	 * @param request
	 */
	private static void renderRequest(URLConnection connection) {

		if (connectTimeout != null) {
			connection.setConnectTimeout(connectTimeout);
		}

		if (socketTimeout != null) {
			connection.setReadTimeout(socketTimeout);
		}

	}
}
